type TreeNode = {
	[key: string]: any;
	children?: TreeNode[];
};

const treeNode = {
	/**
	 * @description 根据id查找树节点
	 * @param {TreeNode[]} tree 树结构数据
	 * @param {string} id 主键值
	 * @param {string} idKey 主键字段名
	 * @returns {TreeNode | null} 匹配到的节点
	 */
	findTreeNode(tree: TreeNode[], id: string, idKey: string = 'id'): TreeNode | null {
		if (!tree || !tree.length) return null;
		for (let i = 0; i < tree.length; i++) {
			if (tree[i][idKey] === id) {
				return tree[i];
			}
			const found = this.findTreeNode(tree[i].children || [], id, idKey);
			if (found) return found;
		}
		return null;
	},
	/**
	 * @description 根据id删除树节点
	 * @param {TreeNode[]} tree 树结构数据
	 * @param {string} id 主键值
	 * @param {string} idKey 主键字段名
	 * @returns {TreeNode[]} 删除后的树结构数据
	 */
	removeTreeNode(tree: TreeNode[], id: string, idKey: string = 'id'): TreeNode[] {
		if (!tree || !tree.length) return [];
		return tree
			.map(node => {
				if (node[idKey] === id) return null;
				if (node.children) {
					node.children = this.removeTreeNode(node.children, id, idKey);
				}
				return node;
			})
			.filter(Boolean) as TreeNode[];
	},
	/**
	 * 查找树形结构中指定ID节点的父节点
	 * @param {TreeNode[]} tree 树形结构数组
	 * @param {string | number} targetId 需要查找的节点ID
	 * @param {Object} config 配置对象
	 * @param {string} config.idField 指定ID字段名 默认 id
	 * @param {string} config.childrenField 指定子节点字段名 默认 children
	 * @returns {TreeNode | null} 目标ID节点的父节点，如果未找到则返回null
	 */
	findParentNode(
		tree: TreeNode[],
		targetId: string | number,
		config: { idField?: string; childrenField?: string } = {}
	): TreeNode | null {
		if (!tree || !tree.length || !targetId) {
			throw new Error(`Invalid data input: tree=>${tree}, targetId=>${targetId}`);
		}
		const currentConfig = {
			idField: 'id',
			childrenField: 'children',
			...config,
		};

		// 递归查找函数
		function searchNode(nodes: TreeNode[], id: string | number): TreeNode | null {
			for (let node of nodes) {
				// 如果当前节点是目标ID
				if (node[currentConfig.idField] === id) {
					return node;
				}
				// 如果当前节点有子节点，继续在子节点中查找
				if (node[currentConfig.childrenField] && node[currentConfig.childrenField].length > 0) {
					const found = searchNode(node[currentConfig.childrenField], id);
					if (found) {
						// 找到目标ID时返回其父节点
						return node;
					}
				}
			}
			// 未找到时返回null
			return null;
		}

		// 开始从根节点查找
		return searchNode(tree, targetId);
	},
};

export default treeNode;
